// component/search/index.js
import { HistoryModel } from '../../model/HistoryModel.js'
import { SearchModel } from '../../model/SerachModel.js'
const historyModel = new HistoryModel()
const searchModel =new SearchModel()
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    
  },

  /**
   * 组件的初始数据
   */
  data: {
    q:'',
    inputValue: '',
    dataArray:[],
    historyArray:[],
    loadingCenter:false,
    searching:false,
    loadingBottom:false,

  },
  attached:function(){
    let historyArray = historyModel.getHistoryItems();
    this.setData({
      historyArray,
      dataArray:[]
    });
  },
  /**
   * 组件的方法列表
   */
  methods: {
    onDelete(event){
      this._initialize();
    },
    onCancel(event){
      this.triggerEvent('onCancel',{},{});
    },
    onTag(event){
      this.onComfirm(event);
    },
    onComfirm(event){
      let value = this.data.inputValue || event.detail.content;
      if (value.length > 0 && !this.data.loadingCenter){
        historyModel.addToHistory(value);
          this.setData({
            loadingCenter: true,
            q:value
          });
          searchModel.postSearch(value).then(res => {
            this.setData({
              dataArray: res.data,
              loadingCenter: false,
              searching:true
            });
          }, err => {
            this.setData({
              loadingCenter: false
            });
          });

      }
    },
    onDetail(event){
      let id = event.currentTarget.dataset.id
      wx.navigateTo({
        url: `/pages/detail/index?id=${id}`,
      })
    },
    bindInput(e){
      this.setData({
        inputValue: e.detail.value
      });
    },
    _initialize(){
      let arr = historyModel.getHistoryItems();
      this.setData({
        historyArray:arr,
        dataArray:[],
        searching:false,
        inputValue:'',
        q:''
      })
    }
  }
})
